<template>
  <div class="purchaser-management">
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">新增采购商</el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="请输入采购商名称、联系人、电话"
        style="width: 300px; margin-left: 16px"
        @keyup.enter="handleSearch"
        clearable />
      <el-button type="primary" @click="handleSearch" style="margin-left: 8px">搜索</el-button>
    </div>

    <base-table
      :data="purchaserList"
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      :loading="loading"
      @page-change="handlePageChange">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="采购商名称" />
      <el-table-column prop="contact" label="联系人" />
      <el-table-column prop="phone" label="联系电话" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="address" label="地址" show-overflow-tooltip />
      <el-table-column prop="companyType" label="公司类型" />
      <el-table-column prop="industry" label="所属行业" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === '合作中' ? 'success' : 'danger'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="handleToggleStatus(row)">
            {{ row.status === "合作中" ? "停用" : "启用" }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </base-table>

    <!-- 采购商表单对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="purchaserForm" label-width="100px">
        <el-form-item label="采购商名称">
          <el-input v-model="purchaserForm.name" />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="purchaserForm.contact" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="purchaserForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="purchaserForm.email" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="purchaserForm.address" type="textarea" />
        </el-form-item>
        <el-form-item label="公司类型">
          <el-input v-model="purchaserForm.companyType" />
        </el-form-item>
        <el-form-item label="所属行业">
          <el-input v-model="purchaserForm.industry" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="purchaserForm.status" :active-value="'合作中'" :inactive-value="'已停用'" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { http } from "@/api";
import BaseTable from "../components/BaseTable.vue";

const purchaserList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchKeyword = ref("");
const loading = ref(false);

const dialogVisible = ref(false);
const dialogTitle = ref("新增采购商");
const purchaserForm = reactive({
  name: "",
  contact: "",
  phone: "",
  email: "",
  address: "",
  companyType: "",
  industry: "",
  status: "合作中",
});

const fetchPurchaserList = async (page = 1) => {
  loading.value = true;
  try {
    const params = {
      page: page,
      size: pageSize.value,
    };
    if (searchKeyword.value.trim()) {
      params.keyword = searchKeyword.value.trim();
    }
    const res = await http.get("/api/purchasers", params);
    purchaserList.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    console.error("获取采购商列表失败:", error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchPurchaserList(currentPage.value);
});

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchPurchaserList(page);
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchPurchaserList(1);
};

const handleAdd = () => {
  dialogTitle.value = "新增采购商";
  // 重置表单数据
  Object.assign(purchaserForm, {
    id: undefined,
    name: "",
    contact: "",
    phone: "",
    email: "",
    address: "",
    companyType: "",
    industry: "",
    status: "合作中",
  });
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogTitle.value = "编辑采购商";
  // 使用解构赋值来避免直接修改原对象
  const { id, name, contact, phone, email, address, companyType, industry, status } = row;
  Object.assign(purchaserForm, {
    id,
    name: name || "",
    contact: contact || "",
    phone: phone || "",
    email: email || "",
    address: address || "",
    companyType: companyType || "",
    industry: industry || "",
    status: status || "合作中",
  });
  dialogVisible.value = true;
};

const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该采购商吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await http.delete(`/api/purchasers/${row.id}`);
      ElMessage.success("删除成功");
      fetchPurchaserList(currentPage.value);
    } catch (error) {
      console.error("删除采购商失败:", error);
    }
  });
};

const handleToggleStatus = (row) => {
  const newStatus = row.status === "合作中" ? "已停用" : "合作中";
  ElMessageBox.confirm(`确定要${row.status === "合作中" ? "停用" : "启用"}该采购商吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await http.patch(`/api/purchasers/${row.id}/status?status=${newStatus}`);
      ElMessage.success(`${newStatus === "合作中" ? "启用" : "停用"}成功`);
      fetchPurchaserList(currentPage.value);
    } catch (error) {
      console.error("更新采购商状态失败:", error);
    }
  });
};

const handleSubmit = async () => {
  try {
    if (dialogTitle.value === "新增采购商") {
      // 新增时不需要id字段
      const { id, ...newPurchaserData } = purchaserForm;
      await http.post("/api/purchasers", newPurchaserData);
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      fetchPurchaserList(currentPage.value);
    } else {
      // 编辑时需要id字段
      await http.put(`/api/purchasers/${purchaserForm.id}`, purchaserForm);
      ElMessage.success("更新成功");
      dialogVisible.value = false;
      fetchPurchaserList(currentPage.value);
    }
  } catch (error) {
    console.error("提交采购商数据失败:", error);
  }
};
</script>

<style scoped>
.purchaser-management {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.operation-bar {
  display: flex;
  align-items: center;
}
</style>
